import React, { Component } from 'react';
import { StyleSheet, Text, View, TouchableOpacity, PixelRatio, DeviceEventEmitter, FlatList } from "react-native";
import { API, API_GENERATE } from '../../../config/api';
import HTTP from '../../../utils/http';
import { GLOBAL } from '../../../config/global';
import { style } from '../../../theme/style';
import { PageStatusIndex } from '../../../component/page-status/PageStatusIndex';
import { Common } from '../../../component/common/Common.js';
import Dictionary from '../../../utils/dictionary';

const scale = GLOBAL.SCALE;
let totalPage = 1;//总的页数
let recordCount = 0;//总的数量

export class RequirementPlanApprovalPage extends Component {
	static navigationOptions = ({ navigation, navigationOptions }) => {
		return {
			headerTitle: '客户需求计划审批',
			headerLeft: <Common type="headLeft" onPress={() => { navigation.goBack() }} />,
			headerTintColor: style.color.dark,
			headerStyle: style.headTow.headerStyleWidthBorder,
			headerTitleStyle: style.headTow.headerTitleStyle,
		}
	};

	constructor(props) {
		super(props);
		this.state = {
			pageStatus: {
				status: 'loading'
			},
			isLoad: true,   // 是否数据加载完成
			emptyResult: false,
			dataSource: [],
			recordCount: 0,   // 数据总条数
			nowList: 0,  // 当前条数
			corpResult: []
		}
		this._fetchStockInfo = this._fetchStockInfo.bind(this);
		this._renderItem = this._renderItem.bind(this);
	}

	async _fetchStockInfo (pageNo, onrefresh) {
		this.setState({
			loadIcon: true
		})
		const responseData = await HTTP.POST(API_GENERATE(API.DAMAND_APPROVAL_LIST), {
			pageNo: pageNo,
			status: 'WAIT'
		}, {
				rejectError: false,
				handleError: true,
			});

		totalPage = responseData.totalPage;

		this.setState({
			isLoad: false,
			loadIcon: false
		})

		if (responseData) {
			if (onrefresh) {  // 刷新
				this.setState({
					dataSource: responseData.rows,
					recordCount: responseData.recordCount,
					nowList: responseData.rows.length
				})
			} else {  // 加载
				this.setState({
					dataSource: this.state.dataSource.concat(responseData.rows),
					recordCount: responseData.recordCount,
					nowList: this.state.nowList + responseData.rows.length
				})
			}
		}
	}

	async componentWillMount () {
		this.pageNo = 1;
		let totalPage = 0;
		await this._fetchStockInfo(this.pageNo, true);

		//审批类型
		let dict = await Dictionary.get('EC_AUDIT_STATUS');
		this.setState({
			corpResult: dict
		})

		this.emitter = DeviceEventEmitter.addListener('requirementListener', async () => {
			console.log('requirementListener');
			this.pageNo = 1;
			totalPage = 1;//总的页数
			recordCount = 0;//总的数量
			this.setState({
				dataSource: [],
				loaded: true,
			});
			await this._fetchStockInfo(this.pageNo, true);
		});
	}

	//数据加载出错回调
	_onErrorPress = () => {
		this.setState({
			status: 'loading'
		}, function () {
			this._getListData();
		})
	}

	//状态-加载前
	_loadFn = () => {
		return (
			<View style={{ flex: 1 }}>
				<PageStatusIndex status="loading" />
			</View>
		)
	}

	//状态-获取到数据
	_bodyFn = () => {
		const { pageStatus, loaded, dataSource, nowList, recordCount } = this.state;
		console.log('dataSource.length', dataSource.length);
		return (
			<View style={styles.container}>

				<View style={[styles.listBox, { marginBottom: 50 * scale }]}>
					{dataSource.length > 0 ? this._renderData() : null}
				</View>
				{
					dataSource.length > 0 ? (<PageStatusIndex status="bottom" recordCount={recordCount} nowList={nowList} />) : null
				}
				{!dataSource || dataSource.length == 0 ? <PageStatusIndex status={"empty"} emptyText="暂无记录" onErrorPress={this._onErrorPress} /> : null}
			</View >
		)
	}

	render () {
		let { isLoad } = this.state;
		if (isLoad) {
			return this._loadFn();
		} else {
			return this._bodyFn();
		}
	}

	_renderData () {
		const { dataSource } = this.state;

		return (
			<FlatList
				data={this.state.dataSource}
				renderItem={this._renderItem.bind(this)}
				onEndReachedThreshold={0.8}
				onEndReached={this._loadData.bind(this)}
				onRefresh={this._isLoadRefresh.bind(this)}
				refreshing={this.state.loadIcon}
			/>
		);

	}

	_renderItem (demand) {
		const { month, status, statusName, createTime, companyName, goodsName, quantity, demandId, deliveryMethod, corpResult, staffName, organName, suggestQuantity } = demand.item;
		const suggestQuantityText = (status == 'PASS') ? <Text style={styles.text} numberOfLines={1}>经营计划部建议量：{suggestQuantity || '无'}</Text> : null;

		return (

			<TouchableOpacity key={demand.index} activeOpacity={0.5} style={styles.demand} onPress={() => {
				this.props.navigation.navigate('RequirementPlanDetailPage', {
					paramsData: { demandId }
				});
			}} >
				<View style={styles.demandHead}>
					<Text style={styles.text}>{companyName}</Text>
					<Text style={styles.statusText}> {statusName}</Text>
				</View>
				<View style={{ flex: 1, flexDirection: 'row', }}>
					<View style={styles.demandCol}>
						<View style={styles.demandRow}>
							<Text style={styles.text} numberOfLines={1}>业务员：{staffName}  {organName}</Text>
						</View>
						<View style={styles.demandRow}>
							<Text style={styles.text} numberOfLines={1}>数量：{quantity}</Text>
						</View>
						<View style={styles.demandRow}>
							<Text style={styles.text} numberOfLines={1}>计划月份：{month}</Text>
						</View>

					</View>
					<View style={styles.demandCol}>
						<View style={styles.demandRow}>
							<Text style={styles.text} numberOfLines={1}>商品名称：{goodsName}</Text>
						</View>
						<View style={styles.demandRow}>
							<Text style={styles.text} numberOfLines={1}>交货方式：{deliveryMethod}</Text>
						</View>
						<View style={styles.demandRow}>
							<Text style={styles.text} numberOfLines={1}>提交时间：{this._getDateStr(createTime)}</Text>
						</View>
						{/*<View style={styles.demandRow}>
							{suggestQuantityText}
		</View>*/}
					</View>

				</View>
			</TouchableOpacity >
		)
	}

	_getDateStr (str) {
		if (str && str.length) {
			const currDate = (typeof str == 'string') ? new Date(str.replace(/-/g, '/')) : str;

			var y = currDate.getFullYear(),
				m = currDate.getMonth() + 1,
				d = currDate.getDate();
			var dateStr = "";
			dateStr += y + "-" + (m < 10 ? "0" + m : m) + "-" + (d < 10 ? "0" + d : d);
			return dateStr;
		} else {
			return '';
		}
	}

	// 下拉更新函数
	_isLoadRefresh () {
		this.pageNo = 1;
		this._fetchStockInfo(this.pageNo, true);
	}

	// 上拉加载
	_loadData () {
		if (totalPage > this.pageNo) {
			this.pageNo++;
			this._fetchStockInfo(this.pageNo, false);
		}
	}

}

const styles = StyleSheet.create({
	statusText: {
		fontSize: 14 * scale,
		color: style.color.themeColor,
	},
	container: {
		flex: 1,
		backgroundColor: '#f5f5f5',
		height: '100%',

	},
	text: {
		fontSize: 12 * scale,
		color: '#4B4B4B'
	},
	demand: {
		backgroundColor: '#fff',
		marginTop: 12 * scale,
		height: 144 * scale,
	},
	demandHead: {
		flexDirection: 'row',
		height: 42 * scale,
		width: 375 * scale,
		justifyContent: 'space-between',
		alignItems: 'center',
		borderBottomColor: '#e4e4e4',
		borderBottomWidth: 1 / PixelRatio.get(),
		paddingLeft: 12 * scale,
		paddingRight: 12 * scale,
	},
	demandCol: {
		flex: 1,
	},
	demandRow: {
		flex: 1,
		justifyContent: 'center',
		paddingLeft: 14 * scale,
	},
	footer: {
		flexDirection: 'row',
		height: 24,
		justifyContent: 'center',
		alignItems: 'center',
		marginBottom: 10,
	},
	noMoreText: {
		color: '#999999',
		fontSize: 14 * scale,
		marginTop: 5 * scale,
		marginBottom: 5 * scale,
	},
	priceListCont: {
		paddingTop: 15 * scale,
		backgroundColor: '#F6F6F6'
	},
	priceListItemCont: {
		paddingTop: 10 * scale,
		paddingBottom: 10 * scale,
		borderBottomWidth: 1 / PixelRatio.get(),
		borderStyle: 'solid',
		borderBottomColor: style.color.border,
		backgroundColor: '#fff'
	},
	priceListItem: {
		flexDirection: 'row',
		alignItems: 'center',
		height: 30 * scale,
		paddingLeft: 15 * scale,
		paddingRight: 15 * scale,
	},
	priceListItemValue: {
		flex: 1,
		fontSize: 13 * scale,
		color: style.color.normal,
	},
	submitBtnCell: {
		height: 60,
		width: '100%',
		justifyContent: 'center',
		alignItems: 'center',
	},
	submitBtn: {
		justifyContent: 'center',
		alignItems: 'center',
		width: 345 * scale,
		height: 44 * scale,
		borderRadius: 100,
		backgroundColor: style.color.themeColor,
	},
	submitBtnText: {
		color: '#fff',
		fontSize: 18 * scale,
	},
})